<?php defined('SYSPATH') or die('No direct script access.');

class registrationHelper {

	public static $MEAL_LIST;

	public static function loadViDisplayData($viRegistration, &$dao) {
		$viRegistration['type'] = 'vi';
		$viSeminar = $dao->getById('vi_seminar', $viRegistration['vi_seminar_id']);
		$priceList = $dao->getByField('vi_seminar_price', 'vi_seminar_id', $viSeminar['id']);
		foreach ($priceList as $price) {
			$viSeminar['prices-' . $price['currency_code']] = $price;
		}
		if ($viRegistration['payment_type'] == 'bank') {
			$viSeminar['bankAccount'] = $dao->getById('bank_account', $viSeminar['bank_account_id']);
		}

		$optionsForm = array();
		$optionsForm['currency_code'] = $viRegistration['currency_code'];
		$optionsForm['viAccomodationType'] = $dao->fetchViAccomodationTypeForSeminar(
				$viSeminar['id'], $viRegistration['vi_accomodation_type_code']);
		$optionsForm['vi_accomodation_type_code'] = $optionsForm['viAccomodationType']['code'];
		$optionsForm['first_meal'] = $viRegistration['first_meal'];
		$optionsForm['last_meal_in_package'] = $viRegistration['last_meal_in_package'];
		$optionsForm['social_discount_applied'] = $viRegistration['social_discount_applied'];
		$optionsForm['total_price'] = $viRegistration['total_price'];
		$optionsForm['accomodation_price'] = $viRegistration['accomodation_price'];
		$optionsForm['meals_price'] = $viRegistration['meals_price'];
		$optionsForm['course_fee'] = $viRegistration['course_fee'];
		$optionsForm['night_count'] = $viRegistration['night_count'];
		$optionsForm['is_instructor'] = $viRegistration['is_instructor'];
		$optionsForm['extra_discount'] = $viRegistration['extra_discount'];
		$optionsForm['is_present'] = ($viRegistration['is_present'] ? sql::$TRUE : sql::$FALSE);

		// Create the meal selection. It may be already created if this method is called from viRegistration.edit
		if ($viRegistration['mealSelection']) {
			$optionsForm['mealSelection'] = $viRegistration['mealSelection'];
		}
		else {
			$selectedMealList = $dao->getByField('vi_registration_meal', 'vi_registration_id', $viRegistration['id']);
			$optionsForm['mealSelection'] = array();
			foreach ($selectedMealList as $selectedMeal) {
				$optionsForm['mealSelection'][] = $selectedMeal['day'] . '_' . $selectedMeal['meal'];
			}
		}

		// From viregWizard.viSeminarNext()
		$viSeminar['bankAccount'] = $dao->getById('bank_account', $viSeminar['bank_account_id']);
		$viSeminar['dayCount'] = seminarHelper::dayCount($viSeminar);

		$viewData = array();

		// From viregWizard.viSeminarNext()
		$viewData['currencyOptions'] = array(
			'CZK' => text::get('currency.CZK')
		);

		$viewData['registration'] = $viRegistration;

		// paymentTypeForm requires payment_type and notes and they are in $viRegistration
		$viewData['paymentTypeForm'] = $viRegistration;
		$viewData['optionsForm'] = $optionsForm;
		$viewData['viSeminar'] = $viSeminar;
		$viewData['bankPaymentDiscount'] = $viRegistration['bank_payment_discount'];

		// Accomodation types
		$viewData['viAccomodationTypeList'] = $dao->fetchViAccomodationTypeListForSeminar($viSeminar['id']);
		$viewData['mealList'] = self::$MEAL_LIST;

		return $viewData;
	}

	public static function mealTableEmptyField($viSeminar, $dayIndex, $meal) {
		if ($dayIndex == 0) {
			if ($viSeminar['first_meal'] == 'lunch') {
				if ($meal == 'breakfast') {
					return TRUE;
				}
			}
			else if ($viSeminar['first_meal'] == 'dinner') {
				if ($meal != 'dinner') {
					return TRUE;
				}
			}
		}
		if ($dayIndex == $viSeminar['dayCount'] - 1) {
			if ($viSeminar['last_meal'] == 'breakfast') {
				if ($meal != 'breakfast') {
					return TRUE;
				}
			}
			else if ($viSeminar['last_meal'] == 'lunch') {
				if ($meal == 'dinner') {
					return TRUE;
				}
			}
		}
		return FALSE;
	}

	public static function getPaymentOptions($viSeminar, $forInstructor, $bankPaymentDiscount, $currencyCode) {
		$paymentOptions = array();
		if ($forInstructor) {
			$paymentOptions['honorarium'] = text::get('viregWizard.paymentType-honorarium');
		}
		else {
			$bankText = text::get('viregWizard.paymentType-bank');
			if (intval($bankPaymentDiscount)) {
				$bankText .= ' - ' . text::get('viregWizard.discount') . ' ' . format::price($bankPaymentDiscount, $currencyCode);
			}
			
			$paymentOptions[''] = '';
			if ($viSeminar['cash_payment_available']) {
				$paymentOptions['cash'] = text::get('viregWizard.paymentType-cash');
			}
			$paymentOptions['bank'] = $bankText;
		}
		return $paymentOptions;
	}

	/**
	 * Processes data from a viRegistration form in viregWizard or admin/viRegistration
	 */
	public static function processSavedForm($optionsForm, $formFromSession, $viSeminar) {
		if (! $viSeminar || ! $viSeminar['prices-' . ViregWizardData::$CURRENCY_CODE]) {
			throw new IncompleteDataException('Seminar does not contain its prices.');
		}
		/*
		if ($optionsForm['is_instructor']) {
			// If we just changed the is_instructor value to True, set the course fee to zero.
			if (! $formFromSession || ! $formFromSession['is_instructor']) {
				$optionsForm['payment_type'] = 'honorarium';
				if ($optionsForm['course_fee'] == $viSeminar['prices-' . $optionsForm['currency_code']]['course_fee']) {
					$optionsForm['course_fee'] = 0;
				}
			}
		}
		else {
			// If is_instructor was just changed to False and the course fee is zero, set it back to the default fee of the seminar.
			if ($formFromSession['is_instructor'] && ! $formFromSession['course_fee']) {
				$optionsForm['course_fee'] = $viSeminar['prices-' . $optionsForm['currency_code']]['course_fee'];
			}
			// Unset the payment type, so that it will be set to the previously
			// saved value in viRegistration.edit()
			unset($optionsForm['payment_type']);
		}
		 */
		return $optionsForm;
	}

	/**
	 * TODO: what is $optionsForm?
	 */
	public static function calculateTotalPrice($viRegistration, $optionsForm, $viSeminarPriceList) {
		$currencyCode = ViregWizardData::$CURRENCY_CODE;
		$totalPrice = $optionsForm['course_fee'];
		if ($optionsForm['course_fee'] === null || trim($optionsForm['course_fee']) == '') {
			// Course fee is in $optionsForm only if the user is an administrator
			$totalPrice = $viSeminarPriceList['course_fee'];
		}

		if ($optionsForm['extra_discount']) {
			$totalPrice = bcsub($totalPrice, $optionsForm['extra_discount']);
		}

		if (! $optionsForm['viAccomodationType'] || ! $optionsForm['viAccomodationType']['price_' . $currencyCode] || is_null($optionsForm['night_count'])) {
			throw new MissingDataException();
		}

		if ($optionsForm['viAccomodationType']) {
			$optionsForm['accomodation_price'] = bcmul(
					$optionsForm['night_count'],
					$optionsForm['viAccomodationType']['price_' . $currencyCode],
					sql::$DECIMAL_PRECISION);
			$totalPrice = bcadd($totalPrice, $optionsForm['accomodation_price'], sql::$DECIMAL_PRECISION);
		}

		$optionsForm['meals_price'] = self::calculateMealsPrice(
				$optionsForm['mealSelection'], $viSeminarPriceList);
		$totalPrice = bcadd($totalPrice, $optionsForm['meals_price'], sql::$DECIMAL_PRECISION);

		if ($optionsForm['social_discount_applied'] == sql::$TRUE) {
			$totalPrice = bcsub($totalPrice, $viSeminarPriceList['social_discount'], sql::$DECIMAL_PRECISION);
		}
		if ($viRegistration['bank_payment_discount']) {
			$totalPrice = bcsub($totalPrice, $viRegistration['bank_payment_discount']);
		}
		if ($viRegistration['early_discount']) {
			$totalPrice = bcsub($totalPrice, $viRegistration['early_discount']);
		}
		$optionsForm['total_price'] = $totalPrice;
		return $optionsForm;
	}

	public static function calculateMealsPrice($selectedMealList, $priceList) {
		$mealSelection = array();
		$meals_price = 0;
		if (is_array($selectedMealList)) {
			foreach ($selectedMealList as $selectedMeal) {
				// $selectedMeal is a meal code in form YYYY-MM-DD_meal
				$meal = substr($selectedMeal, 11);
				$meals_price = bcadd($meals_price, $priceList[$meal . '_price'], sql::$DECIMAL_PRECISION);
			}
		}
		return $meals_price;
	}

	public static function mergeSortRegistrationLists($viRegList, $regList) {
		$regCount = count($regList);
		$viRegCount = count($viRegList);

		if ($regCount + $viRegCount == 0) {
			return array();
		}
		
		// Merge sorting the two registration lists
		$regIndex = 0;
		$viIndex = 0;
		$currentRegistrations = array();
		$pastRegistration = array();
		$registrationList = array();
		while ($regIndex < $regCount || $viIndex < $viRegCount) {
			$reg = NULL; // Registration that will be rendered in this itertaion.
			$regType = NULL;
			if ($regIndex < $regCount && $viIndex < $viRegCount) {
				if (date::diffDates($regList[$regIndex]['seminar_begin_date'], $viRegList[$viRegIndex]['seminar_begin_date']) > 0) {
					$reg = $viRegList[$viRegIndex];
					$viIndex ++;
					$regType = 'vi';
				}
				else {
					$reg = $regList[$regIndex];
					$regIndex ++;
					$regType = 'reg';
				}
			}
			else { 
				if ($regIndex >= $regCount) {
					$reg = $viRegList[$viIndex];
					$viIndex ++;
					$regType = 'vi';
				}
				else {
					$reg = $regList[$regIndex];
					$regIndex ++;
					$regType = 'reg';
				}
			}
			$reg['type'] = $regType;
			$registrationList[] = $reg;
		}
		return $registrationList;
	}

	public static function printMergedRegistrationLists($registrationList, $viRegDisplayMethodUrl, $regDisplayMethodUrl, $openInPopup=FALSE) {
		$today = date::today();
		$pastRegsBlock = FALSE;
		if (date::diffDates($registrationList[0]['seminar_end_date'], $today) <= 0) {
			echo '<h2>' . text::getEscaped('myRegistration.currentRegistrations') . '</h2>';
			echo '<ul class="registrationList">';
		}
		foreach ($registrationList as $index => $reg) {
			if (! $pastRegsBlock && date::diffDates($reg['seminar_end_date'], $today) > 0) {
				// Past registrations
				$pastRegsBlock = TRUE;
				if ($index > 0) {
					echo '</ul>';
				}
				echo '<h2>' . text::getEscaped('myRegistration.pastRegistrations') . '</h2>';
				echo '<ul>';
			}
			echo '<li';
			if ($reg['cancelled_at']) {
				echo ' class="cancelledReg"';
			}
			echo '>';

			$url = ($reg['type'] == 'vi' ? $viRegDisplayMethodUrl : $regDisplayMethodUrl) . '?id=' . $reg['id'] . '&type=' . $reg['type'];
			if ($openInPopup) {
				echo html::moreInfoPopup($url, $reg['seminar_name']);
			}
			else {
				echo html::anchor($url, $reg['seminar_name']);
			}
			echo ' (' . format::date($reg['seminar_begin_date']) . ' - ' . format::date($reg['seminar_end_date']) .  ')';
			if ($reg['cancelled_at']) {
			   echo '<p class="description">' . text::getEscaped('myRegistration.regIsCancelled', format::timestamp($reg['cancelled_at'])) . '</p>';
			}
			echo '</li>';
		}
		echo '</ul>';
	}

	public static function isBankPayment($recordNumber) {
		if ($recordNumber) {
			return preg_match('/^[Bb].*/', $recordNumber);
		}
		return FALSE;
	}

	public static function printSelectedProgramList($selectedProgramList, $removable = false) {
		if (count($selectedProgramList) == 0) {
			return;
		}
		echo '<table class="listTable">' .
			'<thead>';
		$headerList = array('seminarBatch.name', 'seminarBatch.begin_date', 'seminarBatch.end_date', 'programType.entity', 'accomodationType.entity', 'registration.basicPrice');
		foreach ($headerList as $header) {
			echo '<th>' . text::getEscaped($header) . '</th>';
		}
		if ($removable) {
			echo '<th></th>';
		}
		echo '</thead>' .
			'<tbody>';

		foreach ($selectedProgramList as $index => $program) {
			echo '<tr>';
			echo '<td>' . $program['batch']['name'] . '</td>';
			echo '<td>' . format::date($program['batch']['begin_date']) . '</td>';
			echo '<td>' . format::date($program['batch']['end_date']) . '</td>';
			echo '<td>' . $program['programType']['name'] . '</td>';
			echo '<td>' . $program['accomodationType']['name'] . '</td>';
			echo '<td>' . $program['price'] . '</td>';
			if ($removable) {
				echo '<td>' . html::anchor('/user/registrationWizard/removeProgram?index=' . $index, 
					html::img('remove.png', array('title' => text::get('registrationWizard.removeProgram'))), array('onclick' => 'return confirmRemoval();')) . '</td>';
			}
			echo '</tr>';
		}
		echo '</tbody>' .
			'</table>';
	}
	
	public static function printBatchInfo($registration, $batchType) {
		echo '<h3>' . text::getEscaped('registration-batchInfo') . '</h3>';
		$tableData = array(
				text::get('seminarBatch-name') => $registration['batch']['name'],
				text::get('seminarBatch-batch_type_code') => $batchType['name'],
				text::get('seminarBatch-beginning') => format::dateAndTime($registration['batch']['begin_date'], $registration['batch']['begin_time']),
				text::get('seminarBatch-end') => format::dateAndTime($registration['batch']['end_date'], $registration['batch']['end_time']),
		);
		html::displayTable($tableData, false);
	}
	
	public static function printCategoryInfo($registration, $category) {
		echo '<h3>' . text::getEscaped('registration-categoryInfo') . '</h3>';
		$tableData = array(
				text::get('category-program_type_code') => $category['program_type']['name'],
				text::get('category-accomodation_type_code') => $category['accomodation_type']['name']
		);
		if ($registration['room_code']) {
			$tableData[text::get('registration-room_code')] = $registration['room']['name'] . format::longText($registration['room']['description']);
		}
		if ($registration['preferred_karmayoga_type']) {
			$tableData[text::get('registration-preferred_karmayoga_type_code')] = $registration['preferred_karmayoga_type']['name'];
		}
		if ($registration['assigned_karmayoga_type']) {
			$tableData[text::get('registration-assigned_karmayoga_type_code')] = $registration['assigned_karmayoga_type']['name'];
		}
		html::displayTable($tableData, false, true, false);
	}

	public static function printRegistrationDiscounts($seminar, $extraDiscountData, $priceGroup,
			$socialDiscount, $isSocialDiscountApplied,
			$earlyDiscount, $isEarlyDiscountApplied) {

		if ($isSocialDiscountApplied  || $isEarlyDiscountApplied || $extraDiscountData['extra_discount']) {
			echo '<h3>' . text::getEscaped('seminar.discounts') . '</h3>';
			echo '<ul class="readOnlyDiscountList">';
			if ($extraDiscountData['extra_discount']) {
				echo '<li>';
				echo '<em>' . text::getEscaped('registration-extra_discount') . '</em>';
				echo '<p class="description">' . text::getEscaped('registration-extraDiscount-desc') . '</p>';
				
				html::displayTable(array(
						text::get('registration-discountHeight') => format::price($extraDiscountData['extra_discount'], $priceGroup['currency_code']),
						text::get('registration-discountReason') => format::longText($extraDiscountData['extra_discount_reason'])
				), false, true, false);
				
				echo '</li>';
			}
			if ($isSocialDiscountApplied) {
				echo '<li>';
				echo '<em>' . text::getEscaped('seminar.socialDiscount') . '</em>';
				echo '<p class="description">' . text::getEscaped('seminar.socialDiscount-desc') . '</p>';

				echo text::getEscaped('seminar.discountHeight') . ': ' .
						$socialDiscount['percentage'] . '%<br/>';

				if ($isSocialDiscountApplied) {
					echo text::getEscaped('registrationWizard.discountIsApplied') . '<br/>';
				}
				else {
					echo text::getEscaped('registrationWizard.discountIsNotApplied') . '<br/>';
				}

				echo '</li>';
			}
			if ($isEarlyDiscountApplied) {
				echo '<li>';
				echo '<em>' . text::getEscaped('seminar.earlyDiscount') . '</em>';
				echo '<p class="description">' . text::getEscaped('seminar.earlyDiscount-desc') . '</p>';
				?>
				<table class="displayTable">
					<tbody>
						<tr>
							<th><?php echo text::getEscaped('seminar.registration_deadline') ?></th>
							<td><?php echo format::date($seminar['registration_deadline']) ?></td>
						</tr>
						<!--
						<tr>
							<th><?php echo text::getEscaped('seminar.chargeAppliesToKarmayoga') ?></th>
							<td><?php echo format::boolean($earlyDiscount['applies_to_karmayoga']) ?></td>
						</tr>
						-->
						<tr>
							<th><?php echo text::getEscaped('seminar.earlyDiscountPercentage') ?></th>
							<td><?php echo $earlyDiscount['percentage'] ?> %</td>
						</tr>
					</tbody>
				</table>
				<?php
				echo '</li>';
			}
			echo '</ul>';
		}
	}

	public static function printRegistrationPaymentType($country, $organization, $paymentType, $paymentNotes, $onArrivalPaymentFee, $currencyCode) {
		if ($paymentType != 'onArrival') {
			echo '<p class="description">' . text::getEscaped('registration.paymentInCountryOfResidence') . '</p>';
			echo html::displayTable(array(
					text::get('registration.payment_organization_id') => $organization['name'] . ' (' . $country['name'] . ')',
					text::get('registration.payment_type') => text::get('registration.paymentType-' . $paymentType),
					text::get('registration.paymentNotes-header') => $paymentNotes
			));
		}
		else {
			echo '<p class="description">' . text::getEscaped('registration.paymentOnArrival') . '</p>';
			if ($onArrivalPaymentFee) {
				echo html::displayTable(array(
						text::get('registration.paymentOnArrivalFee') => format::price($onArrivalPaymentFee, $currencyCode)
				));
			}
		}
	}

	public static function printRegistrationSeminar($seminar) {
		echo '<h3>' . text::getEscaped('registrationWizard.seminarSummary') . '</h3>';

		echo '<table class="displayTable">';
		echo '<tbody>';

		echo '<tr>';
		echo '<th><label>' . text::getEscaped('seminarBatch.seminar_id') . '</label></th>';
		echo '<td>' . $seminar['name'] . ' <span class="dateTime">' . format::dateAndTime($seminar['begin_date'], $seminar['begin_time']) . ' - ' .
				format::dateAndTime($seminar['end_date'], $seminar['end_time']) . '</span></td>';
		echo '</tr>';

		if ($seminar['description']) {
			echo '<tr>';
			echo '<th><label>' . text::getEscaped('seminar.description') . '</label></th>';
			echo '<td>' . $seminar['description'] . '</td>';
			echo '</tr>';
		}

		echo '</tbody>';
		echo '</table>';
	}
	
	public static function printMetadata($registration) {
		if ($registration['confirmed_at'] || $registration['cancelled_at']) {
			echo '<h3>' . text::getEscaped('registration-metadata') . '</h3>';
			$tableMap = array();
			if ($registration['person_id'] != SessionData::instance()->getAuthUser('id')) {
				$tableMap[text::get('registration-person_id')] = html::escape(format::personFullName($registration['person']));
			}
			if ($registration['confirmed_at']) {
				$tableMap[text::get('registration-confirmed_at')] = format::timestamp($registration['confirmed_at']);
				$tableMap[text::get('registration-confirmed_by_id')] = html::escape(format::personFullName($registration['confirmed_by']));
			}
			if ($registration['cancelled_at']) {
				$tableMap[text::get('registration-cancelled_at')] = format::timestamp($registration['cancelled_at']);
				$tableMap[text::get('registration-cancelled_by_id')] = format::personFullName($registration['cancelled_by']);
				$tableMap[text::get('registration-cancellation_reason')] = format::longText($registration['cancellation_reason']);
			}
			html::displayTable($tableMap, false, true, false);
		}
	}
	
	/**
	 * The registration must be loaded by SeminarService::loadRegistrationDisplayData().
	 */
	public static function printWholeRegistration($registration) {
		// Metadata
		registrationHelper::printMetadata($registration);
		
		// Seminar
		registrationHelper::printRegistrationSeminar($registration['seminar']);
		
		// Batch info
		registrationHelper::printBatchInfo($registration, $registration['batch']['batch_type']);
		
		// Programs
		registrationHelper::printCategoryInfo($registration, $registration['category']);
		
		// Notes
		echo '<h3>' . text::getEscaped('registration-notes') . '</h3>';
		$notesTableModel = array(
				text::get('registration-program_notes') => format::longText($registration['program_notes']),
				text::get('registration-payment_notes') => format::longText($registration['payment_notes'])
		);
		$authUser = SessionData::instance()->getAuthUser();
		if ($registration['person_id'] != $authUser['id'] && ! $authUser['is_admin']) {
			$notesTableModel[text::get('registration-org_notes')] = format::longText($registration['org_notes']);
		}
		html::displayTable($notesTableModel, true, true, false);
		
		// Exercise group, karmayoga type and program notes
		if ($registration['exerciseGroup'] || $registration['karmayogaType'] || $registration['program_notes']) {
			html::displayTable(array(
					text::get('registration.exerciseGroup') => $registration['exerciseGroup']['name'],
					text::get('registration.karmayogaType') => $registration['karmayogaType']['name'],
					text::get('registration.programNotes-header') => $registration['program_notes']
			));
		}
		
		// Prices
		echo '<h2>' . text::getEscaped('registration-price') . '</h2>';
		
		html::displayTable(array(
				text::get('registration-basicPrice') => format::price($registration['category']['price'], $registration['price_group']['currency_code'])
		), false, true, false);
		
		// Discounts
		registrationHelper::printRegistrationDiscounts($registration['seminar'],
				$registration, $registration['price_group'],
				$registration['social_discount'], $registration['social_discount_applied'],
				$registration['early_discount'], $registration['early_discount_applied']);
		
		// Extra charges
		if ($registration['cancellation_fee'] || $registration['late_charge_applied']) {
			echo '<h3>' . text::getEscaped('seminar-extraCharges') . '</h3>';
			echo '<ul class="readOnlyDiscountList">';
			if ($registration['late_charge_applied']) {
				echo '<li>';
				echo '<em>' . text::getEscaped('seminar-lateCharge') . '</em>';
				echo '<p class="description">' . text::getEscaped('seminar-lateCharge-desc') . '</p>';
				?>
				<table class="displayTable">
					<tbody>
						<tr>
							<th><?php echo text::getEscaped('seminar.registration_deadline') ?></th>
							<td><?php echo format::date($seminar['registration_deadline']) ?></td>
						</tr>
						<!--
						<tr>
							<th><?php echo text::getEscaped('seminar.chargeAppliesToKarmayoga') ?></th>
							<td><?php echo format::boolean($registration['late_charge']['applies_to_karmayoga']) ?></td>
						</tr>
						-->
						<tr>
							<th><?php echo text::getEscaped('seminar.lateChargePercentage') ?></th>
							<td><?php echo $registration['late_charge']['percentage'] ?> %</td>
						</tr>
					</tbody>
				</table>
				<?php
				echo '</li>';
			}
			if ($registration['cancellation_fee']) {
				echo '<li>';
				echo '<em>' . text::getEscaped('registration-cancellation_fee') . '</em>';
				html::displayTable(array(
						text::get('registration-chargeHeight') => format::price($registration['cancellation_fee'], $registration['price_group']['currency_code'])
				), false, true, false);
			
				echo '</li>';
			}
			echo '</ul>';
		}
		
		// Total price
		echo '<h3>' . text::getEscaped('registration-finalPrice') . '</h3>';
		$totalPrice = format::price($registration['total_price'], $registration['price_group']['currency_code']);
		if ($registration['cancelled_at']) {
			$totalPriceLabel = text::get('registration-priceWithoutCancellationFee');
			$cancellationFee = '<span class="registrationPrice">' . format::price($registration['cancellation_fee'], $registration['price_group']['currency_code']) . '</span>';
		}
		else {
			$totalPriceLabel = text::get('registration-total_price');
			$totalPrice = '<span class="registrationPrice">' . $totalPrice . '</span>';
		}
			
		html::displayTable(array(
				$totalPriceLabel => $totalPrice,
				text::get('registration-cancellation_fee') => $cancellationFee,
				text::get('registration-price_paid') => '<span class="registrationPrice">' . format::price($registration['price_paid'], $registration['price_group']['currency_code']) . '</span>'
		), true, true, false);
		
		// Payment type
		echo '<h2>' . text::getEscaped('registration.paymentType') . '</h2>';
		registrationHelper::printRegistrationPaymentType(
				$registration['payment_country'],
				$registration['payment_organization'],
				$registration['payment_type'],
				$registration['payment_notes'],
				$registration['payment_on_arrival_fee'],
				$registration['price_group']['currency_code']);
	}
	
	public static function formatPrices($priceList) {
		$formatted = array();
		foreach ($priceList as $currencyCode => $value) {
			$formatted[] = format::price($value, $currencyCode);
		}
		if ($formatted) {
			return join(', ', $formatted);
		}
		return '-';
	}
	
	/**
	 * Value function of a "price_paid" field for an instance of EntityListBuilder class. 
	 */
	public static function pricePaidValue($registration, $entityListField) {
		$value = $entityListField->fieldValue($registration);
	
		$diff = $registration['total_price'] - $registration['price_paid'];
		if ($diff > 0) {
			$value = '<span style="color: red" title="' . text::getEscaped('registration-paidTooLittle', format::price(abs($diff), $registration['currency_code'])) . '">' . $value . '</span>';
		}
		else if ($registration['price_paid'] > $registration['total_price']) {
			$value = '<span style="color: red" title="' . text::getEscaped('registration-paidTooMuch', format::price(abs($diff), $registration['currency_code'])) . '">' . $value . '</span>';
		}
		return $value;
	}
	
	/** Value function for EntityListBuilder. */
	public static function presenceFunction($registration, $entityListField, $url) {
		$html = html::anchor('#',
				format::twoValueBoolean($registration['is_present']),
				array(
						'title' => text::get('registration.togglePresence'),
						'onclick' => "Yosemin.Ajax.partialPageUpdate('" . url::site($url) . "', null, {id:" . $registration['id'] . "}, null); return false;",
						'id' => 'presence_' . $registration['id']
				)
		);
		if (! $registration['confirmed_at']) {
			$html = '! ' . $html . ' !';
		}
		return $html;
	}
	
	/** Value function for EntityListBuilder. */
	public static function keyReturnedFunction($registration, $entityListField, $url) {
		if (strlen($registration['key_deposit']) === 0) {
			return '';
		}
		$html = html::anchor('#',
				format::twoValueBoolean($registration['is_key_returned']),
				array(
						'title' => text::get('registration.togglePresence'),
						'onclick' => "Yosemin.Ajax.partialPageUpdate('" . url::site($url) . "', null, {id:" . $registration['id'] . "}, null); return false;",
						'id' => 'keyRet_' . $registration['id']
				)
		);
		return $html;
	}
	
	/** Value function for EntityListBuilder. */
	public static function keyDepositFunction($registration, $entityListField, $url) {
		$url .= '?id=' . $registration['id'];
		
		$value = $registration['key_deposit'];
		$title = '';
		if ($value) {
			$text = '<span class="description">' . html::escape($value) . '</span> ';
			$link = text::get('common-operation-edit');
			$title = text::getEscaped('common-operation-edit');
		}
		else {
			$link = text::get('common-operation-add');
		}
		return $text . html::popup($url,
				$link,
				array(
						'title' => $title,
						'class' => 'commandInTable'
				)
		);
	}
	
	public static function idCardFunction($registration, $entityListField, $url) {
		$url .= '?id=' . $registration['person_id'];
		$value = $registration['idcard_number'];
		$title = '';
		if ($value) {
			$text = '<span class="description">' . html::escape($value) . '</span> ';
			$link = text::get('common-operation-edit');
			$title = text::getEscaped('common-operation-edit');
		}
		else {
			$link = text::get('common-operation-add');
		}
		return $text . html::popup($url,
				$link,
				array(
						'title' => $title,
						'class' => 'commandInTable'
				)
		);
	}
}

registrationHelper::$MEAL_LIST = array('breakfast', 'lunch', 'dinner');
